package userlogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/logic/role"
	"go-zero-admin/apps/system/cmd/rpc/internal/logic/userpost"
	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/apps/system/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/fx"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/mr"
)

type GetUserDataLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	getRoleIdsByUidLogic *rolelogic.GetRoleIdsByUidLogic
	getUserPostListLogic *userpostlogic.GetUserPostListLogic
}

func NewGetUserDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserDataLogic {
	return &GetUserDataLogic{
		ctx:                  ctx,
		svcCtx:               svcCtx,
		Logger:               logx.WithContext(ctx),
		getRoleIdsByUidLogic: rolelogic.NewGetRoleIdsByUidLogic(ctx, svcCtx),
		getUserPostListLogic: userpostlogic.NewGetUserPostListLogic(ctx, svcCtx),
	}
}

func (l *GetUserDataLogic) GetUserData(in *syspb.GetUserDataReq) (*syspb.GetUserDataResp, error) {
	sysUser, err := l.svcCtx.SysUserModel.FindOne(l.ctx, in.GetId())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("get user data"), err, in)
	}

	// 转换数据
	var user syspb.SysUser
	_ = copier.Copy(&user, sysUser)

	// 处理数据
	var roleIds []int64
	var postIds []int64
	if err = mr.Finish(func() error {
		// 根据用户获取角色信息
		roleIdsResp, err := l.getRoleIdsByUidLogic.GetRoleIdsByUid(
			&syspb.GetRoleIdsByUidReq{UserId: in.GetId()})
		if err != nil {
			return err
		}
		roleIds = roleIdsResp.GetRoleIds()
		return nil
	}, func() error {
		// 根据用户获取岗位信息
		postListResp, err := l.getUserPostListLogic.GetUserPostList(
			&syspb.GetUserPostListReq{UserId: in.GetId()})
		if err != nil {
			return err
		}
		if len(postListResp.GetList()) == 0 {
			return nil
		}

		fx.From(func(source chan<- interface{}) {
			for _, v := range postListResp.GetList() {
				source <- v
			}
		}).Map(func(item interface{}) interface{} {
			return item.(*syspb.SysUserPost).PostId
		}).ForEach(func(item interface{}) {
			postIds = append(postIds, item.(int64))
		})
		return nil
	}); err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DbError),
			tool.GetErrMsgFormat("get user data"), err, in)
	}

	return &syspb.GetUserDataResp{
		User:    &user,
		RoleIds: roleIds,
		PostIds: postIds,
	}, nil
}
